package com.yourname.myapplication.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.databinding.DataBindingUtil
import com.yourname.myapplication.R
import com.yourname.myapplication.databinding.ActivityRegisterBinding
import com.yourname.myapplication.viewmodel.RegisterViewModel

class RegisterActivity : AppCompatActivity() {
    private lateinit var binding: ActivityRegisterBinding
    private lateinit var registerViewModel: RegisterViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_register)

        // 实例化 RegisterViewModel
        registerViewModel = ViewModelProvider(
            this,
            RegisterViewModelFactory(applicationContext)
        ).get(RegisterViewModel::class.java)

        binding.btnRegister.setOnClickListener {
            val username = binding.etUsername.text.toString()
            val password = binding.etPassword.text.toString()

            // 调用 registerUser 方法进行注册
            registerViewModel.registerUser(
                username,
                password,
                onSuccess = {
                    Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show()
                    // 可以在这里添加跳转到登录页面或其他操作
                    val intent = Intent(this, LoginActivity::class.java)
                    startActivity(intent)
                    finish() // 关闭当前注册页面
                     },
                onFailure = { errorMessage ->
                    Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show()
                }
            )
        }

        binding.btnGoToLogin.setOnClickListener {
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
        }
    }
}

// 定义 ViewModelFactory
class RegisterViewModelFactory(private val context: Context) : ViewModelProvider.Factory {
    override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(RegisterViewModel::class.java)) {
            return RegisterViewModel(context) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}